import {defineStore} from 'pinia'
import {computed, ref} from "vue";
import {
    login as loginAPI,
    logout as logoutAPI,
    getUsers as getUsersAPI,
    addUser as addUserAPI,
    updateUser as updateUserAPI,
    deleteUser as deleteUserAPI,

} from '@/apis/user.js'
export const useUserStore = defineStore('userStore', () => {
    //state
    const userInfo = ref({})
    const users = ref([])
    //getters
    const getUserToken = computed(() => {
        return userInfo.value.token
    })
    //actions
    //登录
    const getUserInfo = async ({username, password}) => {
        await loginAPI(username, password)
            .then(res => {
                console.log(res)
                userInfo.value.token = res.accessToken
            })
    }
    //退出登录
    const clearUserInfo = () => {
        userInfo.value = {}
    }
    //获取所有用户
    const fetchUsers= async ()=>{
        try { //调用封装的user。js
            const res = await getUsersAPI()
            // console.log('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@',res)
            users.value = res
            //返回
            return res//响应拦截器配置了data
        } catch (e) {
            throw new Error('获取用户列表失败：' + e.message)
        }
    }
    //添加用户
    const addUser=async (userData)=>{
        try { //调用
            // console.log('Store 发送数据:', userData)
              await addUserAPI(userData)
            //返回
        } catch (e) {
            throw new Error(e.message || '添加用户失败')
        }
    }

    //更新用户信息
    const updateUser = async (userId, userData) =>{
        try { //调用
            const res = await updateUserAPI(userId, userData)
            //更新后立即刷新页面显示在数据上
            //查找本地
            const index = users.value.findIndex(
                user => user.id === userId
            )//index是索引值
            if (index !== -1) {
                users.value[index] = {
                    ...users.value[index],
                }
            }
          // console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@",res)
        } catch (e) {
            throw new Error(e.message || '更新用户失败')
        }
    }
    //删除用户
    const deleteUser = async (userId) => {
        try {
            await deleteUserAPI(userId)
            //更新本地状态
            users.value = users.value.filter(user => user.id !== userId)
        } catch (e) {
            throw new Error(e.message || '删除用户失败')
        }
    }

    return {userInfo, users, getUserInfo, clearUserInfo, getUserToken, fetchUsers,addUser,updateUser,deleteUser}

}, {
    //数据持久化
    persist: true,
})
